package com.ztgf.file.service;

import com.ztgf.common.constant.CommonParameter;
import com.ztgf.common.utils.FileUtils;
import com.ztgf.common.utils.MarkImageUtils;
import com.ztgf.common.utils.StrUtils;
import com.ztgf.file.common.config.YmlConfig;
import com.ztgf.file.fastdfs.FastdfsUtils;
import com.ztgf.file.models.bo.FileBO;
import com.ztgf.file.models.bo.FileInfoSaveBO;
import com.ztgf.file.models.dto.FileInfoDTO;
import com.ztgf.file.models.dto.FileWatermarkDTO;
import com.ztgf.file.models.service.IFileInfoService;
import com.ztgf.file.models.service.IFileService;
import com.ztgf.file.models.vo.FileInfoVO;
import com.ztgf.file.utils.ColorUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import javax.annotation.Resource;
import java.awt.*;

@DubboService
@Slf4j
public class FileServiceImpl implements IFileService {

    public FileServiceImpl() {
    }

    @Autowired
    private IFileInfoService fileInfoService;

    @Autowired
    private FastdfsUtils fastdfsUtils;

    @Resource
    private YmlConfig ymlConfig;

    @Value("${file-http-url}")
    private String fileHtppUrl;

    @Override
    public FileInfoVO uploadImage(FileInfoSaveBO saveBO, FileWatermarkDTO watermarkDTO) throws Exception {

        Long oneTimes = System.currentTimeMillis();
        FileBO fileBO = saveBO.getFileBOS().get(0);
        String result = fastdfsUtils.uploadFileByte(fileBO.getInputs(), fileBO.getFileSize(), fileBO.getFileExtName());
        Long twoTimes = System.currentTimeMillis();
        //上传原文件
        FileInfoDTO dto = new FileInfoDTO();
        dto.setId(ymlConfig.getPkId());
        dto.setFileUserId(saveBO.getPlatId());
        dto.setChildUserId(saveBO.getShopId());
        dto.setType(0);
        dto.setChildType(0);
        dto.setBusinessType(saveBO.getBusinessType());
        dto.setFileUrl(result);
        dto.setFileName(fileBO.getFileName());
        dto.setFileExtName(fileBO.getFileExtName());
        dto.setFileSize(fileBO.getFileSize());
        dto.setIsMark(saveBO.getIsMark());
        fileInfoService.insert(dto);
        Long threeTimes = System.currentTimeMillis();
        if(watermarkDTO != null) {
            doImage(dto, fileBO.getInputs(), watermarkDTO);
        }
        Long foureTimes = System.currentTimeMillis();
        FileInfoVO vo = new FileInfoVO();
        BeanUtils.copyProperties(dto, vo);

        log.info("--文件大小：" + fileBO.getFileSize() + "--上传原图片时长：" + (twoTimes - oneTimes) + "，添加数据库时长："+ (threeTimes - twoTimes) +", 处理水印时长：" + (foureTimes - threeTimes) + ", 上传总时长："+ (foureTimes - oneTimes));
        return vo;
    }

    @Override
    public String batchUploadImage(FileInfoSaveBO saveBO) throws Exception {
        return null;
    }

    @Override
    public FileInfoVO uploadFile(FileInfoSaveBO saveBO) throws Exception {

        FileBO fileBO = saveBO.getFileBOS().get(0);
        log.info("------------------------------file_size------------"+fileBO.getFileSize()+"------------file_name------------"+fileBO.getFileName());
        String result = fastdfsUtils.uploadFileByte(fileBO.getInputs(), fileBO.getFileSize(), fileBO.getFileExtName());
        log.info("------------------------------uploadFile------------true");
        //上传原文件
        FileInfoDTO dto = new FileInfoDTO();
        dto.setId(ymlConfig.getPkId());
        dto.setFileUserId(saveBO.getPlatId());
        dto.setChildUserId(saveBO.getShopId());
        dto.setCreateUserId(saveBO.getShopId());
        dto.setType(1);
        dto.setFileUrl(result);
        dto.setBusinessType(saveBO.getBusinessType());
        dto.setFileName(fileBO.getFileName());
        dto.setFileExtName(fileBO.getFileExtName());
        dto.setFileSize(fileBO.getFileSize());
        dto.setIsMark(saveBO.getIsMark());
        fileInfoService.insert(dto);
        FileInfoVO vo = new FileInfoVO();
        BeanUtils.copyProperties(dto, vo);
        return vo;
    }

    @Override
    public String batchUploadFile(FileInfoSaveBO saveBO) throws Exception {
        return null;
    }

    @Override
    public void doImage(FileInfoDTO dto, byte[] bytes, FileWatermarkDTO watermarkDTO) throws Exception {
        try {
            Long times1 = 0L;
            Long times2 = 0L;

            byte[] markBytes = {};
            //处理水印
            if(watermarkDTO.getType() == 0){//文字
                Color color = Color.RED;
                if(StrUtils.isNotEmpty(watermarkDTO.getFontColor())){
                    color = Color.decode(watermarkDTO.getFontColor());
                }
                Long oneTimes = System.currentTimeMillis();
                markBytes = MarkImageUtils.markText(bytes, watermarkDTO.getWaterName(), watermarkDTO.getFontName(), watermarkDTO.getFontStyle(), watermarkDTO.getFontSize(), color, watermarkDTO.getTransparency(), dto.getFileExtName(), watermarkDTO.getDatumPoint(), watermarkDTO.getPointX(), watermarkDTO.getPointY());
                Long twoTimes = System.currentTimeMillis();
                times1 = twoTimes - oneTimes;
            } else {//图片

                int index = watermarkDTO.getImgUrl().indexOf("/", 2);
                String groupName = watermarkDTO.getImgUrl().substring(1, index);
                String pathName = watermarkDTO.getImgUrl().substring(index + 1);

                byte[]  waterBytes = fastdfsUtils.downFileByte(groupName, pathName);
                markBytes = MarkImageUtils.markImage(bytes, waterBytes, dto.getFileExtName(), watermarkDTO.getDatumPoint(), watermarkDTO.getInclination(), watermarkDTO.getPointX(), watermarkDTO.getPointY());
            }
            int index = dto.getFileUrl().indexOf("/", 2);
            String groupName = dto.getFileUrl().substring(1, index);
            String pathName = dto.getFileUrl().substring(index + 1);
            String childName = "wm";

            long zoomSize = Long.parseLong(markBytes.length + "");
            Long oneTimes = System.currentTimeMillis();
            String zoomImgUrl = fastdfsUtils.uploadSlaveFileStream(groupName, pathName, markBytes, zoomSize, childName,dto.getFileExtName());
            Long twoTimes = System.currentTimeMillis();
            times2 = twoTimes - oneTimes;
            log.info("文件大小：" + zoomSize + "----水印处理时长：" + times1 + "，水印图上传时长："+times2);
            FileInfoDTO zoomDto = new FileInfoDTO();
            BeanUtils.copyProperties(dto, zoomDto);
            zoomDto.setId(ymlConfig.getPkId());
            zoomDto.setFileSize(zoomSize);
            zoomDto.setFileUrl(zoomImgUrl);
            zoomDto.setChildType(1);
            zoomDto.setImgSpecification(childName);
            zoomDto.setProcessStatus(3);
            zoomDto.setWatermark("wm");
            zoomDto.setParentId(dto.getId());
            fileInfoService.insert(zoomDto);

        } catch (Exception e) {
            e.printStackTrace();
            log.error("上传水印文件失败！", e);
        }
    }

    @Override
    public byte[] downloadFile(String filePath) throws Exception {
        int index = filePath.indexOf("/", 2);
        String groupName = filePath.substring(1, index);
        String pathName = filePath.substring(index + 1);
        return fastdfsUtils.downFileByte(groupName, pathName);
    }
}
